package com.atlin.project.controller.cds;

import com.atlin.project.annotation.AuthCheck;
import com.atlin.project.common.BaseResponse;
import com.atlin.project.common.DeleteRequest;
import com.atlin.project.common.ErrorCode;
import com.atlin.project.common.ResultUtils;
import com.atlin.project.contant.UserConstant;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.exception.ThrowUtils;
import com.atlin.project.model.domain.SysUser;
import com.atlin.project.model.domain.cds.ClientCode;
import com.atlin.project.model.dto.clientCode.ClientCodeAddRequest;
import com.atlin.project.model.dto.clientCode.ClientCodeQueryRequest;
import com.atlin.project.model.dto.clientCode.ClientCodeUpdateRequest;
import com.atlin.project.model.vo.cds.CdsSyncCheckVo;
import com.atlin.project.model.vo.cds.ClientCodeVO;
import com.atlin.project.service.SysUserService;
import com.atlin.project.service.ClientCodeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 客户端标识控制
 *
 * @author atlin
 */
@RestController
@RequestMapping("/clientCode")
public class ClientCodeController {

    @Resource
    private ClientCodeService clientCodeService;

    @Resource
    private SysUserService sysUserService;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param clientCodeAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addClientCode(@RequestBody ClientCodeAddRequest clientCodeAddRequest, HttpServletRequest request) {
        if (clientCodeAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ClientCode clientCode = new ClientCode();
        BeanUtils.copyProperties(clientCodeAddRequest, clientCode);

        clientCodeService.valid(clientCode, true);
//        SysUser loginUser = sysUserService.getLoginUser(request);

        // todo

        ClientCode one = clientCodeService.getOne(new LambdaQueryWrapper<ClientCode>()
                .eq(ClientCode::getCode, clientCode.getCode())
                .eq(ClientCode::getUserId, clientCode.getUserId()));

        if (one != null) {
            clientCode.setId(one.getId());
        }
        boolean result = clientCodeService.saveOrUpdate(clientCode);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newClientCodeId = clientCode.getId();
        return ResultUtils.success(newClientCodeId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteClientCode(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysUser user = sysUserService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        ClientCode oldclientCode = clientCodeService.getById(id);
        ThrowUtils.throwIf(oldclientCode == null, ErrorCode.NULL_ERROR);

        // 仅本人或管理员可删除
        if (!oldclientCode.getUserId().equals(user.getId()) && !sysUserService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = clientCodeService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param clientCodeUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateClientCode(@RequestBody ClientCodeUpdateRequest clientCodeUpdateRequest) {
        if (clientCodeUpdateRequest == null || clientCodeUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ClientCode clientCode = new ClientCode();
        BeanUtils.copyProperties(clientCodeUpdateRequest, clientCode);

        // 参数校验
        clientCodeService.valid(clientCode, false);
        long id = clientCodeUpdateRequest.getId();
        // 判断是否存在
        ClientCode oldclientCode = clientCodeService.getById(id);
        ThrowUtils.throwIf(oldclientCode == null, ErrorCode.NULL_ERROR);
        // todo other operation

        boolean result = clientCodeService.updateById(clientCode);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<ClientCode> getClientCodeById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ClientCode clientCode = clientCodeService.getById(id);
        if (clientCode == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        SysUser loginUser = sysUserService.getLoginUser(request);
        // 不是本人或管理员，不能直接获取所有信息
        if (!clientCode.getUserId().equals(loginUser.getId()) && !sysUserService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(clientCode);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ClientCodeVO> getClientCodeVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ClientCode clientCode = clientCodeService.getById(id);
        if (clientCode == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        ClientCodeVO clientCodeVO = ClientCodeVO.objToVo(clientCode);
        return ResultUtils.success(clientCodeVO);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param clientCodeQueryRequest 查询参数
     * @param request                查询请求
     * @return 分页封装类
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ClientCodeVO>> listClientCodeVOByPage(@RequestBody ClientCodeQueryRequest clientCodeQueryRequest,
                                                                   HttpServletRequest request) {
        long current = clientCodeQueryRequest.getCurrent();
        long size = clientCodeQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<ClientCode> clientCodePage = clientCodeService.page(new Page<>(current, size),
                clientCodeService.getQueryWrapper(clientCodeQueryRequest));

        Page<ClientCodeVO> clientCodeVOPage = clientCodeService.getClientCodeVOPage(clientCodePage, request);

        return ResultUtils.success(clientCodeVOPage);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param clientCodeQueryRequest 查询参数
     * @param request                查询请求
     * @return 分页
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ClientCode>> listClientCodeByPage(@RequestBody ClientCodeQueryRequest clientCodeQueryRequest,
                                                               HttpServletRequest request) {
        long current = clientCodeQueryRequest.getCurrent();
        long size = clientCodeQueryRequest.getPageSize();
        Page<ClientCode> clientCodePage = clientCodeService.page(new Page<>(current, size),
                clientCodeService.getQueryWrapper(clientCodeQueryRequest));
        return ResultUtils.success(clientCodePage);
    }

    // endregion


    /**
     * 客户端文件同步校验
     *
     * @param clientCode 客户端标识码
     * @return CdsSyncCheckVo
     */
    @GetMapping("/syncCheck")
    public List<CdsSyncCheckVo> syncCheck(String clientCode) {
        if (StringUtils.isBlank(clientCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<CdsSyncCheckVo> res = clientCodeService.syncCheck(clientCode);
        return res;
    }
}
